package com.csg.ses.feign;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csg.ses.common.configuration.SesConfig;
import com.csg.ses.common.utils.CommonUtil;
import com.csg.ses.common.utils.RedisUtil;
import com.csg.ses.dao.ses.YxzjkKhYhzhDao;
import com.csg.ses.dao.ses.YxzjkLcCbxxDao;
import com.csg.ses.dao.ses.YxzjkZwCsxxDao;
import com.csg.ses.entity.ses.YxzjkKhYhzhEntity;
import com.csg.ses.entity.ses.YxzjkLcCbxxEntity;
import com.csg.ses.entity.ses.YxzjkZwCsxxEntity;
import com.csg.ses.service.ses.SysInterfaceLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @auther wangjun
 * @time 2020/11/17 15:50
 * vcs机器人接口调用
 */
@Service
@EnableConfigurationProperties(SesConfig.class)
public class VcsService {

    private String[] interfaceAddressArr = {
            "/vcs_api/openapi/getToken.php",
            "/vcs_api/openapi/getProjectList.php",
            "/vcs_api/openapi/createTask.php",
            "/vcs_api/openapi/pustPhones.php",
            "/vcs_api/openapi/resume.php",
            "/vcs_api/openapi/pause.php",
            "/vcs_api/openapi/getTaskList.php",
            "/vcs_api/openapi/getPhoneRun.php"
    };

    private String[] interfaceNameArr = {
            "获取token",
            "获取机器人模板",
            "创建任务",
            "添加外呼号码",
            "任务启动",
            "任务暂停",
            "获取任务列表",
            "获取任务详情"
    };

    @Autowired
    private SesConfig sesConfig;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SysInterfaceLogService logService;

    @Autowired
    private YxzjkZwCsxxDao sesCsxxDao;

    @Autowired
    private YxzjkKhYhzhDao sesYhzhDao;

    @Autowired
    private YxzjkLcCbxxDao sesCbxxDao;

    @Autowired
    private PhpService phpService;

    /**
     * 获取vcs接口数据    http://10.150.175.54
     * @param interfaceNo   接口序号
     *        0.获取token      /vcs_api/openapi/getToken.php
     *        1.获取机器人模板   /vcs_api/openapi/getProjectList.php
     *        2.创建任务        /vcs_api/openapi/createTask.php
     *        3.添加外呼号码     /vcs_api/openapi/pustPhones.php
     *        4.任务启动        /vcs_api/openapi/resume.php
     *        5.任务暂停        /vcs_api/openapi/pause.php
     *        6.获取任务列表     /vcs_api/openapi/getTaskList.php
     *        7.获取任务详情     /vcs_api/openapi/getPhoneRun.php
     * @param params    接口参数
     * @return
     */
    public JSONObject getVcsDatas(int interfaceNo, JSONObject params) {
        String address = "http://10.150.175.54" + interfaceAddressArr[interfaceNo]; //接口地址
        String interfaceName = interfaceNameArr[interfaceNo];   //接口名称
        String inParams = params.toJSONString().length() <= 200 ? params.toJSONString() : params.toJSONString().substring(0, 200) + "......";  //入参
        Long logId = logService.insertLog(interfaceName, address, "vcs", new String[] {inParams});    //插入日志记录
        Boolean isSuccess = false;
        String[] outParams = {"接口调用成功！"};

        try {
            ResponseEntity<String> exchange = null;
            if (interfaceNo == 0) exchange = phpService.getToken(params);               //获取token
            if (interfaceNo == 1) exchange = phpService.getRobotTemplate(params);       //获取机器人模板
            if (interfaceNo == 2) exchange = phpService.createTask(params);             //创建任务
            if (interfaceNo == 3) exchange = phpService.pustPhones(params);             //添加外呼号码
            if (interfaceNo == 4) exchange = phpService.resume(params);                 //任务启动
            if (interfaceNo == 5) exchange = phpService.pause(params);                  //任务暂停
            if (interfaceNo == 6) exchange = phpService.getTaskList(params);            //获取任务列表
            if (interfaceNo == 7) exchange = phpService.getTaskDetails(params);         //获取任务详情

            JSONObject result = JSON.parseObject(exchange.getBody());
            if ("1".equals(result.getString("code"))) {
                outParams = new String[] {result.toJSONString()};
            } else {
                isSuccess = true;
            }
            return result;
        } catch (Exception e) {
            outParams = new String[] {"调用" + address + "接口失败！", e.getCause().getMessage()};
            e.printStackTrace();
            throw new RuntimeException(outParams[0]);
        } finally {
            logService.updateLog(logId, isSuccess, outParams);  //更新日志记录
        }
    }

    /**
     * 获取token
     * @return
     */
    public String getToken() {
        if (redisUtil.exists("vcs_access_token")) {
            return String.valueOf(redisUtil.get("vcs_access_token"));
        } else {
            JSONObject params = new JSONObject();
            params.put("access", sesConfig.getAccess());
            params.put("pass", sesConfig.getPass());

            JSONObject result = this.getVcsDatas(0, params);
            if ("1".equals(result.getString("code"))) {
                throw new RuntimeException(result.getString("info"));
            } else {
                JSONObject data = JSON.parseObject(result.getString("data"));
                String access_token = data.getString("access_token");
                Long expires_in = data.getLong("expires_in");
                try {
                    redisUtil.set("vcs_access_token", access_token, expires_in, TimeUnit.SECONDS);
                    return access_token;
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException();
                }
            }
        }
    }

    /**
     * 获取机器人模板
     * @return
     */
    public JSONArray getProjectList() {
        JSONObject params = new JSONObject();
        params.put("access", sesConfig.getAccess());
        params.put("token", this.getToken());

        JSONObject result = this.getVcsDatas(1, params);
        if ("1".equals(result.getString("code"))) {
            throw new RuntimeException(result.getString("info"));
        } else {
            JSONArray data = JSON.parseArray(result.getString("data"));
            return data;
        }
    }

    /**
     * 创建任务
     * @param dqbm
     * @param yxpch
     * @return
     */
    public String createTask(String dqbm, String yxpch) {
        JSONObject params = new JSONObject();
        params.put("access", sesConfig.getAccess());
        params.put("token", this.getToken());

        /*JSONArray projectList = this.getProjectList();  //获取机器人模板
        String projectId = "152";
        String projectName = null;
        if (projectList != null && projectList.size() > 0) {
            projectId = projectList.getJSONObject(0).getString("id");
            projectName = projectList.getJSONObject(0).getString("pro_name");
        } else {
            throw new RuntimeException("未查询到机器人模板！");
        }*/
        params.put("project", "152");
        params.put("task_name", "自动_" + this.getDqmcByDqbm(dqbm) + "_" + yxpch);
        params.put("start_time", "09:00");
        params.put("end_time", "18:30");
        params.put("sleep_stime", "12:00");
        params.put("sleep_etime", "14:00");

        JSONObject result = this.getVcsDatas(2, params);
        if ("1".equals(result.getString("code"))) {
            throw new RuntimeException(result.getString("info"));
        } else {
            JSONObject data = JSON.parseObject(result.getString("data"));
            String task_id = data.getString("task_id");
            return task_id;
        }
    }

    /**
     * 添加外呼号码
     * @param dqbm
     * @param yxpch
     * @param csxxList
     * @return task_id
     */
    public String pustPhones(String dqbm, String yxpch, List<YxzjkZwCsxxEntity> csxxList) {
        JSONObject params = new JSONObject();
        String task_id = this.createTask(dqbm, yxpch);
        params.put("access", sesConfig.getAccess());
        params.put("token", this.getToken());
        params.put("task_id", task_id);

        JSONArray phones = new JSONArray();
        for (YxzjkZwCsxxEntity csxx : csxxList) {
            //银行账号
            QueryWrapper<YxzjkKhYhzhEntity> qw1 = new QueryWrapper<>();
            qw1.eq("YXPCH", csxx.getYxpch());
            qw1.eq("JSHH", csxx.getJshh());
            List<YxzjkKhYhzhEntity> yhzhList = sesYhzhDao.selectList(qw1);

            //抄表信息
            QueryWrapper<YxzjkLcCbxxEntity> qw2 = new QueryWrapper<>();
            qw2.eq("YXPCH", csxx.getYxpch());
            qw2.eq("YHBH", csxx.getYhbh());
            qw2.eq("DFNY", csxx.getDfny());
            List<YxzjkLcCbxxEntity> cbxxList = sesCbxxDao.selectList(qw2);

            JSONObject phone = new JSONObject();
            phone.put("phone", csxx.getSjhm());
            phone.put("busines", "");

            JSONObject variable = new JSONObject();
            variable.put("应收电费", csxx.getQf());
            variable.put("用电类別", csxx.getYdlb());
            variable.put("应收电量", csxx.getYsdl());
            variable.put("电费年月", csxx.getDfny());
            if (yhzhList != null && yhzhList.size() > 0) {
                variable.put("联网银行", yhzhList.get(0).getLwyh());
                variable.put("银行账号", yhzhList.get(0).getYhzh());
            }
            variable.put("供电单位", csxx.getGddw());
            variable.put("欠违约金", csxx.getQwyj());
            variable.put("用户编号", csxx.getYhbh());
            variable.put("客户经理电话号码", csxx.getKhjldhhm());
            if (cbxxList != null && cbxxList.size() > 0) {
                variable.put("抄表底数", cbxxList.get(0).getBcbss());
            }
            variable.put("用电地址", csxx.getYddz());
            variable.put("用户名称", csxx.getYhmc());

            phone.put("variable", variable);
            phones.add(phone);
        }
        params.put("phones", phones);

        JSONObject result = this.getVcsDatas(3, params);
        if ("1".equals(result.getString("code"))) {
            throw new RuntimeException(result.getString("info"));
        } else {
            return task_id;
        }
    }

    /**
     * 任务启动、任务暂停
     * @param task_id   任务id
     * @param start     是否启动
     * @return
     */
    public Boolean resumeOrPause(String task_id, Boolean start) {
        Boolean flag = true;
        JSONObject params = new JSONObject();
        params.put("access", sesConfig.getAccess());
        params.put("token", this.getToken());
        params.put("task_id", task_id);
        JSONObject result = null;
        if (start) {
            result = this.getVcsDatas(4, params);
        } else {
            result = this.getVcsDatas(5, params);
        }

        try {
            if ("1".equals(result.getString("code"))) {
                flag = false;
                throw new RuntimeException(result.getString("info"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return flag;
        }
    }

    /**
     * 获取任务列表
     * @param task_id
     * @param task_status 任务状态，取值：run 运行中，pause 暂停中，finish 已完成
     * @return
     */
    public JSONArray getTaskList(String task_id, String task_status) {
        JSONObject params = new JSONObject();
        params.put("access", sesConfig.getAccess());
        params.put("token", this.getToken());
        if (!CommonUtil.isEmpty(task_id)) {
            params.put("task_id", task_id);
        }
        if (!CommonUtil.isEmpty(task_status)) {
            params.put("task_status", task_status);
        }

        JSONObject result = this.getVcsDatas(6, params);
        if ("1".equals(result.getString("code"))) {
            throw new RuntimeException(result.getString("info"));
        } else {
            JSONArray data = JSON.parseArray(result.getString("data"));
            return data;
        }
    }

    /**
     * 获取任务详情
     * @param task_id
     * @param call_status   呼叫状态，取值：0 未呼叫，1呼叫中，2成功 , 3 失败，4 未接听 ，6、7号码准备中
     * @param pageSize      每页记录数（等于批次的记录数）
     * @return
     */
    public JSONArray getPhoneRun(String task_id, String call_status, String pageSize) {
        JSONObject params = new JSONObject();
        params.put("access", sesConfig.getAccess());
        params.put("token", this.getToken());
        params.put("task_id", task_id);
        if (!CommonUtil.isEmpty(call_status)) {
            params.put("call_status", call_status);
        }
        params.put("page_size", pageSize);
        params.put("page", "1");

        JSONObject result = this.getVcsDatas(7, params);
        if ("1".equals(result.getString("code"))) {
            throw new RuntimeException(result.getString("info"));
        } else {
            JSONArray data = JSON.parseArray(JSON.parseObject(result.getString("data")).get("list").toString());
            return data;
        }
    }

    /**
     * 根据地区编码获取地区名称
     * @param dqbm
     * @return
     */
    public String getDqmcByDqbm(String dqbm) {
        String dqmc = "";
        LinkedHashMap<String, String> dqMap = new LinkedHashMap<>();
        dqMap.put("030200", "韶关供电局");
        dqMap.put("030400", "珠海供电局");
        dqMap.put("030500", "汕头供电局");
        dqMap.put("030600", "佛山供电局");
        dqMap.put("030700", "江门供电局");
        dqMap.put("030800", "湛江供电局");
        dqMap.put("030900", "茂名供电局");
        dqMap.put("031200", "肇庆供电局");
        dqMap.put("031300", "惠州供电局");
        dqMap.put("031400", "梅州供电局");
        dqMap.put("031500", "汕尾供电局");
        dqMap.put("031600", "河源供电局");
        dqMap.put("031700", "阳江供电局");
        dqMap.put("031800", "清远供电局");
        dqMap.put("031900", "东莞供电局");
        dqMap.put("032000", "中山供电局");
        dqMap.put("035100", "潮州供电局");
        dqMap.put("035200", "揭阳供电局");
        dqMap.put("035300", "云浮供电局");
        if (dqbm != null && dqMap.containsKey(dqbm)) {
            dqmc = dqMap.get(dqbm);
        }
        return dqmc;
    }
}